require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');

// 设置Mongoose选项以消除警告
mongoose.set('strictQuery', true);

// 路由
const userRoutes = require('./routes/users');
const roomRoutes = require('./routes/rooms');
const transactionRoutes = require('./routes/transactions');

const app = express();

// 连接数据库
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/poker_accounting')
  .then(() => console.log('数据库连接成功'))
  .catch(err => console.error('数据库连接失败:', err));

// 中间件
app.use(cors());
app.use(express.json());

// 路由
app.use('/api/users', userRoutes);
app.use('/api/rooms', roomRoutes);
app.use('/api/transactions', transactionRoutes);

// 健康检查
app.get('/health', (req, res) => {
  res.json({ 
    message: '打牌记账系统运行正常', 
    timestamp: new Date().toISOString(),
    version: '1.0.0'
  });
});

// API文档
app.get('/api', (req, res) => {
  res.json({
    name: '打牌记账系统 API',
    version: '1.0.0',
    description: '多人实时打牌记账系统后端API',
    endpoints: {
      users: '/api/users',
      rooms: '/api/rooms',
      transactions: '/api/transactions'
    }
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({ message: '接口不存在' });
});

// 错误处理
app.use((err, req, res, next) => {
  console.error('服务器错误:', err);
  res.status(500).json({ message: '服务器内部错误' });
});

const PORT = process.env.PORT || 3000;

// 启动服务器
app.listen(PORT, () => {
  console.log(`🚀 打牌记账系统服务器运行在端口 ${PORT}`);
  console.log(`📡 API地址: http://localhost:${PORT}/api`);
});

// 优雅关闭
process.on('SIGTERM', () => {
  console.log('收到SIGTERM信号，正在关闭服务器...');
  mongoose.connection.close(() => {
    console.log('数据库连接已关闭');
    process.exit(0);
  });
});

process.on('SIGINT', () => {
  console.log('收到SIGINT信号，正在关闭服务器...');
  mongoose.connection.close(() => {
    console.log('数据库连接已关闭');
    process.exit(0);
  });
}); 